from django.core.cache import cache

from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View

from areas.models import Area


class ProvinceAreasView(View):
    def get(self, request):
        province_list = cache.get('province_list')
        if not province_list:
            try:
                provinces = Area.objects.filter(parent__isnull=True)
                province_list = []
                for province in provinces:
                    province_list.append({'id': province.id,
                                          'name': province.name})
                cache.set('province_list', province_list, 3600)

            except Exception as e:
                return JsonResponse({'code': 400,
                                     'errmsg': '获取数据失败'})
        return JsonResponse({'code': 0,
                             'errmsg': 'ok',
                             'province_list': province_list})


class SubAreasView(View):
    def get(self, request, pk):
        sub_data = cache.get('sub_area_' + pk)
        if not sub_data:
            try:
                subs = Area.objects.filter(parent=pk)
                province = Area.objects.get(id=pk)
                sub_list = []
                for sub in subs:
                    sub_list.append({
                        'id': sub.id,
                        'name': sub.name
                    })
                    sub_data = {
                        'id': province.id,
                        'name': province.name,
                        'subs': sub_list
                    }
                cache.set('sub_area_' + pk, sub_data, 3600)

            except Exception as e:
                return JsonResponse({'code': 400,
                                     'errmsg': '获取数据失败'})

        return JsonResponse({'code': 0,
                             'errmsg': 'ok',
                             'sub_data': sub_data})
